import { defineStore } from 'pinia'
import type { Teacher } from '../types/Teacher'

/**
 * 教师信息存储模块
 * 负责管理教师信息的全局状态
 */
export const useTeacherStore = defineStore('teacher', {
    state: () => ({
        // 所有教师列表
        teachers: [] as Teacher[],
        // 当前选中的教师
        currentTeacher: null as Teacher | null,
        // 加载状态
        loading: false,
        // 搜索关键词
        searchKeyword: ''
    }),
    actions: {
        /**
         * 获取所有教师信息
         */
        async fetchAllTeachers() {
            this.loading = true
            try {
                // this.teachers = await teacherApi.getAllTeachers()
            } finally {
                this.loading = false
            }
        },

        /**
         * 获取教师详情
         * @param teacherId - 教师ID
         */
        async fetchTeacherDetail(teacherId: number) {
            this.loading = true
            try {
                // this.currentTeacher = await teacherApi.getTeacherDetail(teacherId)
            } finally {
                this.loading = false
            }
        },

        /**
         * 更新教师信息
         * @param updatedTeacher - 更新后的教师信息
         */
        async updateTeacher(updatedTeacher: Teacher) {
            this.loading = true
            try {
                // const updated = await teacherApi.updateTeacher(updatedTeacher)
                // const index = this.teachers.findIndex(t => t.teacherId === updated.teacherId)
                // if (index !== -1) {
                //     this.teachers[index] = updated
                // }
            } finally {
                this.loading = false
            }
        },

        /**
         * 设置搜索关键词
         * @param keyword - 搜索关键词
         */
        setSearchKeyword(keyword: string) {
            this.searchKeyword = keyword
        }
    },
    getters: {
        /**
         * 获取筛选后的教师列表
         */
        filteredTeachers(state): Teacher[] {
            if (!state.searchKeyword.trim()) return state.teachers

            const keyword = state.searchKeyword.toLowerCase()
            return state.teachers.filter(teacher =>
                teacher.teacherName.toLowerCase().includes(keyword) ||
                (teacher.title && teacher.title.toLowerCase().includes(keyword)) ||
                (teacher.major && teacher.major.toLowerCase().includes(keyword))
            )
        },

        /**
         * 按职称分组的教师统计
         */
        teachersByTitle(state) {
            const groups = new Map<string, number>()
            state.teachers.forEach(teacher => {
                const title = teacher.title || '未设置'
                groups.set(title, (groups.get(title) || 0) + 1)
            })
            return Array.from(groups.entries())
        }
    }
})
